<?php

namespace stlswm\DouyinOpenApi\pay\ecpay;

use stlswm\DouyinOpenApi\CurlHttp;
use stlswm\DouyinOpenApi\Response;

/**
 * 担保支付-支付-预下单
 * https://developer.open-douyin.com/docs/resource/zh-CN/mini-app/develop/server/ecpay/pay-list/pay
 */
class CreateOrder
{
    use CurlHttp;

    private static string $url     = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_order';
    private static string $urlTest = 'https://open-sandbox.douyin.com/api/apps/ecpay/v1/create_order';

    public string $app_id;
    public string $out_order_no;
    public int    $total_amount;
    public string $subject;
    public string $body;
    public int    $valid_time;
    public string $cp_extra;
    public string $notify_url;
    public string $thirdparty_id;
    public string $store_uid;
    public int    $disable_msg;
    public string $msg_page;
    public array  $expand_order_info;
    public string $limit_pay_way;

    /**
     * @param  string  $salt
     * @param  array   $body       请求体
     * @param  bool    $inSandBox  是否沙盒测试环境
     * @return Response
     */
    public function send(string $salt, array &$body = [], bool $inSandBox = false): Response
    {
        $allowKeys = [
            'app_id',
            'out_order_no',
            'total_amount',
            'subject',
            'body',
            'valid_time',
            'sign',
            'cp_extra',
            'notify_url',
            'thirdparty_id',
            'store_uid',
            'disable_msg',
            'msg_page',
            'expand_order_info',
            'limit_pay_way',
        ];
        foreach ($allowKeys as $key) {
            if (isset($this->$key)) {
                $body[$key] = $this->$key;
            }
        }
        $body['sign'] = Sign::sign($salt, $body);

        return self::postJson($inSandBox ? self::$urlTest : self::$url, $body);
    }

}